// 创建Vue应用
new Vue({
    el: '#app',
    data() {
        return {
            // UI状态
            isCollapse: false,
            currentModule: 'user', // 'user'或'proxy'

            // ===== 用户管理相关数据 =====
            users: [],
            userLoading: false,
            userPagination: {
                page: 1,
                pageSize: 10,
                total: 0
            },
            userFilters: {
                username: '',
                browserType: ''
            },
            detailDialogVisible: false,
            currentUser: null,
            userBrowserComposites: [],
            currentEmployee: null,
            expirationDialogVisible: false,
            expirationForm: {
                browserID: '',
                time: null
            },
            activateBrowserDialogVisible: false,
            activateForm: {
                username: '',
                baseBrowserAccount: '',
                activateTime: null
            },
            activateRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                baseBrowserAccount: [
                    { required: true, message: '请输入基础浏览器账号', trigger: 'blur' }
                ],
                activateTime: [
                    { required: true, message: '请选择有效期', trigger: 'change' }
                ]
            },
            activateSubmitting: false,
            activateResult: null,

            // ===== 代理管理相关数据 =====
            proxies: [],
            proxyLoading: false,
            proxyPagination: {
                page: 1,
                pageSize: 10,
                total: 0
            },
            proxyFilters: {
                proxyIP: '',
                proxyUser: '',
                proxyType: ''
            },
            proxyDialogVisible: false,
            proxyDialogTitle: '添加代理',
            isEditMode: false,
            proxyForm: {
                id: '',
                proxyType: 'http',
                proxyIP: '',
                proxyPort: '',
                proxyUser: '',
                proxyPassword: '',
                proxyTagID: '',
                note: ''
            },
            proxyRules: {
                proxyType: [
                    { required: true, message: '请选择代理类型', trigger: 'change' }
                ],
                proxyIP: [
                    { required: true, message: '请输入代理IP', trigger: 'blur' },
                    { pattern: /^(\d{1,3}\.){3}\d{1,3}$|([\w-]+\.)+[\w-]+/, message: '请输入有效的IP地址或域名', trigger: 'blur' }
                ],
                proxyPort: [
                    { required: true, message: '请输入代理端口', trigger: 'blur' },
                    { pattern: /^\d+$/, message: '端口必须是数字', trigger: 'blur' }
                ]
            },
            submitLoading: false,
            syncDialogVisible: false,
            syncResult: null,
            currentProxy: null,
            applyProxyDialogVisible: false,
            selectedUsers: [],
            userSearchKeyword: '',
            selectAllUsers: false,
            applyLoading: false,
            applyResult: [],
            proxyApplicationHistory: [],

            // 新增：用于应用代理的浏览器数据
            availableBrowsers: [],
            selectedBrowsers: [],
            browserSearchKeyword: '', // 新增浏览器搜索关键词
            selectAllBrowsers: false // 新增全选浏览器状态
        };
    },
    computed: {
        // 活动菜单项
        activeMenu() {
            return this.currentModule;
        },
        
        // 过滤后的用户列表(应用代理时使用)
        filteredUsers() {
            if (!this.users) {
                return [];
            }
            
            // 过滤用户
            let result = this.users;
            
            if (this.userSearchKeyword) {
                const keyword = this.userSearchKeyword.toLowerCase();
                result = result.filter(user => 
                    user.username.toLowerCase().includes(keyword)
                );
            }
            
            // 如果有应用历史记录，标记已应用的用户
            if (this.proxyApplicationHistory && this.proxyApplicationHistory.length > 0) {
                // 输出日志，帮助调试
                console.log('应用历史记录示例：', this.proxyApplicationHistory[0]);
                console.log('用户列表示例：', this.users[0]);
                
                // 整理应用历史记录，按用户ID分组
                const historyMap = {};
                this.proxyApplicationHistory.forEach(item => {
                    // 确保取到正确的用户ID
                    const userId = item.UserID || item.userId || item.user_id;
                    if (!userId) {
                        console.warn('历史记录中缺少用户ID字段：', item);
                        return;
                    }
                    
                    if (!historyMap[userId]) {
                        historyMap[userId] = [];
                    }
                    historyMap[userId].push(item);
                });
                
                // 标记用户
                result = result.map(user => {
                    const userHistory = historyMap[user.userId] || [];
                    const latestHistory = userHistory.length > 0 ? userHistory[0] : null;
                    
                    return {
                        ...user,
                        // 标记最近是否应用成功
                        lastApplied: latestHistory ? {
                            success: latestHistory.Success,
                            time: latestHistory.CreatedAt,
                            message: latestHistory.Message
                        } : null
                    };
                });
            }
            
            return result;
        },
        
        // 过滤后的浏览器列表(应用代理时使用)
        filteredBrowsers() {
            if (!this.availableBrowsers) {
                return [];
            }
            
            let result = this.availableBrowsers;
            
            if (this.browserSearchKeyword) {
                const keyword = this.browserSearchKeyword.toLowerCase();
                result = result.filter(browser => 
                    (browser.browserName && browser.browserName.toLowerCase().includes(keyword)) ||
                    (browser.browserType && browser.browserType.toLowerCase().includes(keyword)) ||
                    (browser.username && browser.username.toLowerCase().includes(keyword)) ||
                    (browser.groupName && browser.groupName.toLowerCase().includes(keyword))
                );
            }

            // 不再需要处理上次应用历史标记，因为现在是基于浏览器的
            
            return result;
        }
    },
    created() {
        // 根据URL判断当前模块
        const path = window.location.pathname;
        if (path.includes('/admin/proxy')) {
            this.currentModule = 'proxy';
            this.loadProxies();
        } else {
            this.currentModule = 'user';
            this.loadUsers();
        }
    },
    methods: {
        // ===== 通用方法 =====
        
        // 切换侧边栏折叠状态
        toggleSidebar() {
            this.isCollapse = !this.isCollapse;
        },
        
        // 切换模块
        switchModule(module) {
            if (this.currentModule === module) return;
            
            this.currentModule = module;
            
            // 更新URL和浏览器历史
            const path = module === 'user' ? '/admin/' : '/admin/proxy';
            window.history.pushState(null, '', path);
            
            // 加载相应数据
            if (module === 'user') {
                this.loadUsers();
            } else {
                this.loadProxies();
            }
        },
        
        // 格式化日期
        formatDate(dateStr) {
            if (!dateStr) return '-';
            const date = new Date(dateStr);
            return date.toLocaleString('zh-CN', { 
                year: 'numeric', 
                month: '2-digit', 
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        },

        // ===== 用户管理方法 =====
        
        // 获取浏览器标签类型
        getBrowserTagType(type) {
            if (!type) return 'info';
            const typeMap = {
                'chrome': 'primary',
                'firefox': 'success',
                'safari': 'warning',
                'edge': 'info'
            };
            const lcType = type.toLowerCase();
            return typeMap[lcType] || 'info';
        },
        
        // 表格行样式
        tableRowClassName({row}) {
            if (row.isActive === false) {
                return 'inactive-row';
            }
            return '';
        },
        
        // 重置用户筛选条件
        resetUserFilters() {
            this.userFilters = {
                username: '',
                browserType: ''
            };
            this.loadUsers();
        },
        
        // 加载用户列表
        loadUsers() {
            this.userLoading = true;
            
            const params = {
                page: this.userPagination.page,
                pageSize: this.userPagination.pageSize,
                username: this.userFilters.username,
                browserType: this.userFilters.browserType
            };
            
            axios.get('/admin/api/users', { params })
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        const data = response.data.data || {};
                        this.users = data.list || [];
                        this.userPagination.total = data.total || 0;
                    } else {
                        this.$message.error(response.data?.message || '加载失败');
                        this.users = [];
                    }
                })
                .catch(error => {
                    console.error('Error loading users:', error);
                    this.$message.error('加载用户失败，请检查网络连接');
                    this.users = [];
                })
                .finally(() => {
                    this.userLoading = false;
                });
        },
        
        // 处理用户页面大小变化
        handleUserSizeChange(size) {
            this.userPagination.pageSize = size;
            this.loadUsers();
        },
        
        // 处理用户页码变化
        handleUserCurrentChange(page) {
            this.userPagination.page = page;
            this.loadUsers();
        },
        
        // 显示用户详情
        showDetail(row) {
            this.detailDialogVisible = true;
            this.currentUser = null;
            this.userBrowserComposites = [];
            this.currentEmployee = null;
            this.userLoading = true;
            
            axios.get(`/admin/api/users/${row.userId}`)
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        const data = response.data.data || {};
                        this.currentUser = data.user || null;
                        this.userBrowserComposites = data.groups || [];
                        this.currentEmployee = data.employee || null;
                    } else {
                        this.$message.error(response.data?.message || '获取用户详情失败');
                    }
                })
                .catch(error => {
                    console.error('Error loading user details:', error);
                    this.$message.error('获取用户详情失败，请检查网络连接');
                })
                .finally(() => {
                    this.userLoading = false;
                });
        },
        
        // 显示更新过期时间对话框
        showUpdateExpiration(browserID) {
            this.expirationDialogVisible = true;
            this.expirationForm = {
                browserID: browserID,
                time: Date.now() + 30 * 24 * 60 * 60 * 1000 // 默认30天后
            };
        },
        
        // 更新浏览器过期时间
        updateExpiration() {
            if (!this.expirationForm.time) {
                this.$message.warning('请选择过期时间');
                return;
            }
            
            this.userLoading = true;
            
            axios.put(`/admin/api/browsers/${this.expirationForm.browserID}/expiration`, {
                expiration_time: this.expirationForm.time
            })
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.$message.success(response.data.message || '更新过期时间成功');
                        this.expirationDialogVisible = false;
                        
                        // 刷新用户详情
                        if (this.currentUser) {
                            this.showDetail({ userId: this.currentUser.id });
                        }
                    } else {
                        this.$message.error(response.data?.message || '更新过期时间失败');
                    }
                })
                .catch(error => {
                    console.error('Error updating expiration:', error);
                    this.$message.error('更新过期时间失败，请检查网络连接');
                })
                .finally(() => {
                    this.userLoading = false;
                });
        },
        
        // 确认删除当前用户
        confirmDeleteCurrentUser() {
            if (!this.currentUser) return;
            
            this.$confirm(`确定要删除用户 ${this.currentUser.username} 吗? 此操作不可恢复!`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteUser(this.currentUser.id);
            }).catch(() => {
                // 用户取消删除
            });
        },
        
        // 确认删除用户
        confirmDeleteUser(row) {
            this.$confirm(`确定要删除用户 ${row.username} 吗? 此操作不可恢复!`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteUser(row.userId);
            }).catch(() => {
                // 用户取消删除
            });
        },
        
        // 删除用户
        deleteUser(id) {
            this.userLoading = true;
            
            axios.delete(`/admin/api/users/${id}`)
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.$message.success(response.data.message || '删除成功');
                        
                        // 如果是当前详情中的用户，关闭详情对话框
                        if (this.currentUser && this.currentUser.id === id) {
                            this.detailDialogVisible = false;
                        }
                        
                        // 刷新用户列表
                        this.loadUsers();
                    } else {
                        this.$message.error(response.data?.message || '删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error deleting user:', error);
                    this.$message.error('删除用户失败，请检查网络连接');
                })
                .finally(() => {
                    this.userLoading = false;
                });
        },
        
        // 触发过期用户检查
        triggerExpiredCheck() {
            this.userLoading = true;
            
            axios.post('/admin/api/check-expired-users')
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.$message.success(response.data.message || '检查已触发');
                        // 检查完成后刷新用户列表
                        this.loadUsers();
                    } else {
                        this.$message.error(response.data?.message || '触发检查失败');
                    }
                })
                .catch(error => {
                    console.error('Error triggering expired check:', error);
                    this.$message.error('触发检查失败，请检查网络连接');
                })
                .finally(() => {
                    this.userLoading = false;
                });
        },
        
        // 显示激活浏览器对话框
        showActivateBrowserDialog() {
            this.activateBrowserDialogVisible = true;
            this.activateForm = {
                username: '',
                baseBrowserAccount: '',
                activateTime: Date.now() + 30 * 24 * 60 * 60 * 1000 // 默认30天后
            };
            this.activateResult = null;
            this.activateSubmitting = false;
        },
        
        // 提交激活浏览器
        submitActivate() {
            this.$refs.activateForm.validate(valid => {
                if (!valid) {
                    return false;
                }
                
                this.activateSubmitting = true;
                
                // 准备符合后端期望格式的请求数据
                const requestData = {
                    username: this.activateForm.username,
                    base_browser_account: this.activateForm.baseBrowserAccount,
                    activate_time: Math.floor(this.activateForm.activateTime / 1000)
                };
                
                axios.post('/admin/api/activate-browser', requestData)
                    .then(response => {
                        // 检查后端响应码判断是否成功
                        const isSuccess = response.data && response.data.code === 200;

                        // 构造 activateResult 对象，包含 success 标志和后端数据
                        this.activateResult = {
                            ...response.data, // 保留原始响应数据
                            success: isSuccess // 明确设置 success 标志给 UI
                        };

                        if (isSuccess) {
                            // 激活成功后刷新用户列表
                            this.loadUsers();
                        }
                        // 不需要 else，因为 isSuccess 为 false 时，UI 会自动显示失败
                    })
                    .catch(error => {
                        console.error('Error activating browser:', error);
                        // 构造包含 success: false 的错误对象
                        this.activateResult = {
                            success: false, // 明确设置 success 为 false
                            code: error.response?.status || 500,
                            message: `激活失败: ${error.response?.data?.message || error.message}`,
                            data: null // 错误时 data 为 null
                        };
                    })
                    .finally(() => {
                        this.activateSubmitting = false;
                    });
            });
        },

        // ===== 代理管理方法 =====
         // 新方法：加载应用代理对话框的浏览器列表
         loadBrowsersForProxyDialog() {
            this.applyLoading = true; // 开始加载
            this.availableBrowsers = []; // 先清空

            axios.get('/admin/api/browsers/for-proxy') // 不再需要传 proxyId
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.availableBrowsers = response.data.data || [];
                        console.log('可用浏览器列表加载/刷新成功，数量:', this.availableBrowsers.length);
                    } else {
                        this.$message.error(response.data?.message || '加载浏览器列表失败');
                        this.availableBrowsers = [];
                    }
                })
                .catch(error => {
                    console.error('加载浏览器列表失败:', error);
                    this.$message.error('加载浏览器列表失败，请检查网络连接');
                    this.availableBrowsers = [];
                })
                .finally(() => {
                    this.applyLoading = false; // 结束加载
                });
        },
        // 应用代理时的表格单元格合并方法
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            // 只合并"窗口名称"(即 browserType) 列
            if (columnIndex === 2) { // 假设"窗口名称"是第3列 (索引从0开始)
                const prevRow = this.filteredBrowsers[rowIndex - 1];
                // 如果是第一行或者当前行的类型与上一行不同
                if (rowIndex === 0 || row.browserType !== prevRow.browserType) {
                    let rowspan = 1;
                    // 向下查找有多少行具有相同的类型
                    for (let i = rowIndex + 1; i < this.filteredBrowsers.length; i++) {
                        if (this.filteredBrowsers[i].browserType === row.browserType) {
                            rowspan++;
                        } else {
                            break;
                        }
                    }
                    return {
                        rowspan: rowspan,
                        colspan: 1
                    };
                } else {
                    // 如果当前行类型与上一行相同，则隐藏此单元格
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
            }
            // 其他列不合并
            return {
                rowspan: 1,
                colspan: 1
            };
        },

        // 根据代理类型获取标签颜色类型
        getProxyTypeTagType(type) {
            if (!type) return 'info';
            const typeMap = {
                'http': 'primary',
                'socks5': 'success',
                'ssh': 'warning'
            };
            return typeMap[type.toLowerCase()] || 'info';
        },
        
         // 获取应用代理对话框中浏览器表格行的类名
         getBrowserRowClassName({row, rowIndex}) {
            let classes = []; // 使用数组存储可能存在的多个类名

            // --- 添加分组开始行判断 ---
            const prevRow = this.filteredBrowsers[rowIndex - 1];
            // 如果是第一行或者当前行的类型与上一行不同，则为分组开始行
            if (rowIndex === 0 || row.browserType !== prevRow.browserType) {
                classes.push('group-start-row');
            }
            // -------------------------

            // --- 保留之前的代理匹配判断 ---
            if (this.currentProxy && this.currentProxy.ID) {
                if (row.currentProxy && row.currentProxy.proxyId) {
                    if (row.currentProxy.proxyId === this.currentProxy.ID) {
                        classes.push('proxy-match-row'); // 匹配
                    } else {
                        classes.push('proxy-mismatch-row'); // 不匹配
                    }
                }
            } else if (!this.currentProxy || !this.currentProxy.ID) {
                 console.warn('Current proxy ID is missing for row class calculation.');
            }
            // ---------------------------

            return classes.join(' '); // 返回所有类名，用空格分隔
        },

        // 重置代理筛选条件
        resetProxyFilters() {
            this.proxyFilters = {
                proxyIP: '',
                proxyUser: '',
                proxyType: ''
            };
            this.loadProxies();
        },
        
        // 加载代理列表
        loadProxies() {
            this.proxyLoading = true;
            
            const params = {
                page: this.proxyPagination.page,
                pageSize: this.proxyPagination.pageSize,
                proxyIP: this.proxyFilters.proxyIP,
                proxyUser: this.proxyFilters.proxyUser,
                proxyType: this.proxyFilters.proxyType
            };
            
            axios.get('/admin/api/proxies', { params })
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        const data = response.data.data || {};
                        // 检查数据结构并正确解析
                        if (data.list && Array.isArray(data.list)) {
                            // 需要对每个代理对象的字段进行处理，从后端返回的数据转为前端需要的格式
                            this.proxies = data.list.map(proxy => {
                                // 如果属性名已经是首字母大写的，就不需要转换
                                if (proxy.ProxyType) {
                                    return proxy;
                                }
                                
                                // 将小驼峰字段名转换为首字母大写格式
                                return {
                                    ID: proxy.id || proxy.ID,
                                    ProxyType: proxy.proxyType || proxy.proxy_type || "",
                                    ProxyIP: proxy.proxyIP || proxy.proxy_ip || "",
                                    ProxyPort: proxy.proxyPort || proxy.proxy_port || "",
                                    ProxyUser: proxy.proxyUser || proxy.proxy_user || "",
                                    ProxyPassword: proxy.proxyPassword || proxy.proxy_password || "",
                                    TagIDs: proxy.tagIDs || proxy.tag_ids || proxy.proxyTagID || "",
                                    Note: proxy.note || "",
                                    Active: proxy.active !== undefined ? proxy.active : true
                                };
                            });
                        } else {
                            this.proxies = [];
                        }
                        this.proxyPagination.total = data.total || 0;
                    } else {
                        this.$message.error(response.data?.message || '加载失败');
                        this.proxies = [];
                    }
                })
                .catch(error => {
                    console.error('Error loading proxies:', error);
                    this.$message.error('加载代理失败，请检查网络连接');
                    this.proxies = [];
                })
                .finally(() => {
                    this.proxyLoading = false;
                });
        },
        
        // 处理代理页面大小变化
        handleProxySizeChange(size) {
            this.proxyPagination.pageSize = size;
            this.loadProxies();
        },
        
        // 处理代理页码变化
        handleProxyCurrentChange(page) {
            this.proxyPagination.page = page;
            this.loadProxies();
        },
        
        // 显示创建代理对话框
        showCreateProxyDialog() {
            this.isEditMode = false;
            this.proxyDialogTitle = '添加代理';
            this.proxyForm = {
                id: '',
                proxyType: 'http',
                proxyIP: '',
                proxyPort: '',
                proxyUser: '',
                proxyPassword: '',
                proxyTagID: '',
                note: ''
            };
            this.proxyDialogVisible = true;
            this.$nextTick(() => {
                this.$refs.proxyForm && this.$refs.proxyForm.clearValidate();
            });
        },
        
        // 显示更新代理对话框
        showUpdateProxyDialog(proxy) {
            this.isEditMode = true;
            this.proxyDialogTitle = '编辑代理';
            this.proxyForm = {
                id: proxy.ID,
                proxyType: proxy.ProxyType,
                proxyIP: proxy.ProxyIP,
                proxyPort: proxy.ProxyPort,
                proxyUser: proxy.ProxyUser,
                proxyPassword: proxy.ProxyPassword,
                proxyTagID: proxy.TagIDs,
                note: proxy.Note
            };
            this.proxyDialogVisible = true;
            this.$nextTick(() => {
                this.$refs.proxyForm && this.$refs.proxyForm.clearValidate();
            });
        },
        
        // 提交代理表单
        submitProxyForm() {
            this.$refs.proxyForm.validate(valid => {
                if (!valid) {
                    return false;
                }
                
                this.submitLoading = true;
                
                // 根据是否是编辑模式选择API
                const api = '/admin/api/proxies';
                const method = this.isEditMode ? 'put' : 'post';
                
                axios[method](api, this.proxyForm)
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.$message.success(response.data.message || '操作成功');
                            this.proxyDialogVisible = false;
                            this.loadProxies();
                        } else {
                            this.$message.error(response.data?.message || '操作失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error submitting proxy form:', error);
                        this.$message.error(`操作失败: ${error.response?.data?.message || error.message}`);
                    })
                    .finally(() => {
                        this.submitLoading = false;
                    });
            });
        },
        
        // 确认删除代理
        confirmDeleteProxy(proxy) {
            this.$confirm(`确定要删除代理 ${proxy.ProxyIP}:${proxy.ProxyPort} 吗?`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteProxy(proxy.ID);
            }).catch(() => {
                // 用户取消删除
            });
        },
        
        // 删除代理
        deleteProxy(id) {
            this.proxyLoading = true;
            
            axios.delete(`/admin/api/proxies/${id}`)
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.$message.success(response.data.message || '删除成功');
                        this.loadProxies();
                    } else {
                        this.$message.error(response.data?.message || '删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error deleting proxy:', error);
                    this.$message.error(`删除失败: ${error.response?.data?.message || error.message}`);
                })
                .finally(() => {
                    this.proxyLoading = false;
                });
        },
        
        // 同步代理
        syncProxies() {
            this.proxyLoading = true;
            
            axios.post('/admin/api/proxies/sync')
                .then(response => {
                    if (response.data && response.data.code === 200) {
                        this.syncResult = {
                            message: response.data.message,
                            total: response.data.data?.total || 0,
                            syncCount: response.data.data?.syncCount || 0
                        };
                        this.syncDialogVisible = true;
                        this.loadProxies();
                    } else {
                        this.$message.error(response.data?.message || '同步失败');
                    }
                })
                .catch(error => {
                    console.error('Error syncing proxies:', error);
                    this.$message.error(`同步失败: ${error.response?.data?.message || error.message}`);
                })
                .finally(() => {
                    this.proxyLoading = false;
                });
        },
        
       // 显示应用代理对话框
       showApplyProxyDialog(proxy) {
        this.currentProxy = proxy;
        this.applyProxyDialogVisible = true;
        this.applyResult = [];
        this.selectedBrowsers = []; // 清空已选浏览器
        this.selectAllBrowsers = false;
        this.browserSearchKeyword = '';
        
        // 调用新方法加载浏览器列表
        this.loadBrowsersForProxyDialog(); 
    },
        // 处理全选浏览器
        handleSelectAllBrowsers(val) {
            if (val) {
                // 全选当前过滤后的浏览器
                this.selectedBrowsers = [...this.filteredBrowsers]; 
            } else {
                // 取消全选
                this.selectedBrowsers = [];
            }
            // 手动触发 table 的 selection 更新 (重要)
            this.$nextTick(() => {
                 const table = this.$refs.browserSelectionTable; // 需要在 el-table 上设置 ref="browserSelectionTable"
                 if (table) {
                     this.filteredBrowsers.forEach(row => {
                         table.toggleRowSelection(row, val);
                     });
                 }
            });
        },
        
        // 处理浏览器选择变化
        handleBrowserSelectionChange(val) {
            this.selectedBrowsers = val;
            
            // 更新全选状态
            if (this.filteredBrowsers.length > 0) {
                this.selectAllBrowsers = val.length === this.filteredBrowsers.length;
            } else {
                this.selectAllBrowsers = false;
            }
        },
        
     // 应用代理到选定的浏览器
     applyProxyToSelectedBrowsers() {
        if (this.selectedBrowsers.length === 0) {
            this.$message.warning('请至少选择一个浏览器');
            return;
        }
        
        this.applyLoading = true; // 开始应用时也显示加载状态
        this.applyResult = [];
        
        // 收集所有选定的浏览器ID (UUID)
        const browserIds = this.selectedBrowsers.map(browser => browser.browserId);
        
        // 构造请求数据
        const requestData = {
            proxyId: this.currentProxy.ID,
            browserIds: browserIds
        };
        
        // 发送请求应用代理到浏览器
        axios.post('/admin/api/proxies/apply-to-browsers', requestData)
            .then(response => {
                if (response.data && response.data.code === 200) {
                    this.$message.success(response.data.message || '应用代理处理完成');
                    this.applyResult = response.data.data || [];
                    
                    // 应用成功后，调用新方法重新加载浏览器列表以更新状态
                    this.loadBrowsersForProxyDialog(); 
                    
                } else {
                    this.$message.error(response.data?.message || '应用代理失败');
                    // 失败时也应该停止 loading
                    this.applyLoading = false;
                }
            })
            .catch(error => {
                console.error('Error applying proxy to browsers:', error);
                this.$message.error(`应用代理失败: ${error.response?.data?.message || error.message}`);
                this.applyLoading = false; // 出错时停止 loading
            });
            // .finally 的 loading 处理移到 loadBrowsersForProxyDialog 中
    },
        // 获取成功率 (基于 applyResult)
        getSuccessRate() {
            if (this.applyResult.length === 0) return '0%';
            
            const successCount = this.applyResult.filter(item => item.success).length;
            const rate = (successCount / this.applyResult.length * 100).toFixed(1);
            return `${rate}%`;
        }
    }
}); 